// eslint-disable-next-line
import * as loginService from '@/api/login'
// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'
import { bxAnaalyse } from '@/core/icons'
import { defaultRoute} from '@/config/defaultRoute.config'
// 前端路由表
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  '403': () => import(/* webpackChunkName: "error" */ '@/views/exception/403'),
  '404': () => import(/* webpackChunkName: "error" */ '@/views/exception/404'),
  '500': () => import(/* webpackChunkName: "error" */ '@/views/exception/500'),

  // 你需要动态引入的页面组件
  'Analysis': () => import('@/views/dashboard/Analysis'),
  // exception
  'Exception403': () => import(/* webpackChunkName: "fail" */ '@/views/exception/403'),
  'Exception404': () => import(/* webpackChunkName: "fail" */ '@/views/exception/404'),
  'Exception500': () => import(/* webpackChunkName: "fail" */ '@/views/exception/500'),

  // account
  'AccountSettings': () => import('@/views/account/settings/Index'),
  'BaseSettings': () => import('@/views/account/settings/BaseSetting'),
  'SecuritySettings': () => import('@/views/account/settings/Security'),
  'CustomSettings': () => import('@/views/account/settings/Custom'),
  'BindingSettings': () => import('@/views/account/settings/Binding'),
  'NotificationSettings': () => import('@/views/account/settings/Notification'),
}

import { Notification } from "@/views/account/settings/Notification"


// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}

// 根级菜单
const rootRouter = {
  key: '',
  name: 'index',
  path: '',
  component: 'BasicLayout',
  redirect: '/dashboard',
  meta: {
    title: '首页'
  },
  children: []
}

const account = {
  path: '/account',
  name: 'account',
  redirect: '/account/settings/base',
  component: RouteView,
  meta: { title: '商城设置', icon: 'user', keepAlive: true, permission: ['user'] },
  children: [
    {
      path: '/account/settings',
      name: 'settings',
      component: () => import('@/views/account/settings/Index'),
      meta: { title: '商城设置', hideHeader: true, permission: ['user'] },
      redirect: '/account/settings/base',
      hideChildrenInMenu: true,
      children: [
        {
          path: '/account/settings/base',
          name: 'BaseSettings',
          component: constantRouterComponents['BaseSettings'],
          meta: { title: '基本设置', permission: ['user'] }
        },
        {
          path: '/account/settings/security',
          name: 'SecuritySettings',
          component: constantRouterComponents['SecuritySettings'],
          meta: { title: '安全设置', keepAlive: true, permission: ['user'] }
        },
        {
          path: '/account/settings/custom',
          name: 'CustomSettings',
          component: constantRouterComponents['CustomSettings'],
          meta: { title: '个性化设置', keepAlive: true, permission: ['user'] }
        },
        {
          path: '/account/settings/binding',
          name: 'BindingSettings',
          component: constantRouterComponents['BindingSettings'],
          meta: { title: '账户绑定', keepAlive: true, permission: ['user'] }
        },
        {
          path: '/account/settings/notification',
          name: 'NotificationSettings',
          component: constantRouterComponents['NotificationSettings'],
          meta: { title: '新消息通知', keepAlive: true, permission: ['user'] }
        }
      ]
    }
  ]
}

const index = {
  path: '/dashboard',
  name: 'dashboard',
  redirect: '/dashboard/analysis',
  component: RouteView,
  meta: { title: '仪表盘', keepAlive: true, icon: bxAnaalyse, permission: ['dashboard'] },
  children: [
    {
      path: '/dashboard/analysis',
      name: 'Analysis',
      component: () => import('@/views/dashboard/Analysis'),
      meta: { title: '分析页', keepAlive: false, permission: ['dashboard'] }
    },
  ]
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (token) => {
  return new Promise((resolve, reject) => {
    loginService.getCurrentUserNav(token).then(res => {
      // console.log('res', res)
      const result = res.data
      const menuNav = []
      const childrenNav = []
      //      后端数据, 根级树数组,  根级 PID
      // console.log(result)
      listToTree(result, childrenNav, -1)
      // console.log('childrenNav',childrenNav)
      rootRouter.children = childrenNav
      menuNav.push(rootRouter)
      // console.log('menuNav', menuNav)
      const routers = generator(menuNav)
      routers.push(notFoundRouter)
      // console.log('routers', routers)
      defaultRoute.forEach(i=>{  //动态加入默认自定义路由
        index.children.push(i)
      })
      routers[0].children.unshift(index)
      routers[0].children.push(account)
      // console.log('routers', routers)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}

    // console.log("item.component")
    // console.log(item.component)
    // console.log("item.path")
    // console.log(item.path)

    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${parent && parent.path || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',

      // 该路由对应页面的 组件 :方案1
      //component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      // component: constantRouterComponents[item.component || item.key] || () => import(`@/views/${item.component}`), component(resolve) { require([`../${item.path}.vue`], resolve) },
      component: constantRouterComponents[item.component || item.key] ? constantRouterComponents[item.component || item.key] : resolve => require([`@/views${item.path}.vue`], resolve),
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: { title: title, icon: icon || undefined, hiddenHeaderContent: hiddenHeaderContent, target: target, permission: item.name }
    }
    // 是否设置了隐藏菜单
    if (show === false) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {

      const child = {
        ...item,
        path: item.path,
        name: item.name,
        component(resolve) { require([`../${item.path}.vue`], resolve) },
        key: item.key || item.name,
        children: item.children,
        //显示图标
        meta: { title: item.name, keepAlive: true, icon: bxAnaalyse }
      }

      // console.log('child',child)
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      if (child.children.length > 0) {
        const subChildrenNav = []
        // console.log(child.children)
        listToTree(item.children, subChildrenNav, item.id)
        child.children = subChildrenNav
      }
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }

      // 加入到树中
      tree.push(child)
    }
  })
}
